<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <SearchForm v-show="showSearch" v-model="queryParams" :options="options.formOps" @onQuery="getList">
        </SearchForm>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['preventionHiddenRegister:create']">新增</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="warning" plain @click="handlePush()"
              >推送隐患数据</el-button
            >
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <Table ref="table" :auto-featch="true" :fetch-data="fetchData" :options="options.table" action-width="150"
          @selectionChange="selectionChange">
          <template #beforehiddenLevel>
            <el-table-column label="装置" prop="deviceId" align="center" width="150" key="deviceId" show-overflow-tooltip>
              <template #default="{ row }">
                {{ columnZz(row.deviceId) }}
              </template>
            </el-table-column>
            <el-table-column label="隐患分类" prop="hiddenType" align="center" width="150" key="hiddenType"
              show-overflow-tooltip>
            </el-table-column>
          </template>
          <template #afterhiddenRectificationMeasures>
            <el-table-column label="整改责任人" prop="rectificationUserName" align="center" width="150"
              key="rectificationUserName">
            </el-table-column>

            <el-table-column label="复核人" width="150" prop="reviewUserName" align="center" key="reviewUserName">
            </el-table-column>
            <el-table-column label="审批状态" width="150" prop="reviewUserName" align="center" key="reviewUserName">
              <template #default="{ row }">
                <span v-if="row.hiddenState == 1">已通过</span>
                <span v-else-if="row.hiddenState == 2">已驳回</span>
                <span v-else-if="row.hiddenState == 3">待修改</span>
                <span v-else>待审核</span>
              </template>
            </el-table-column>
            <el-table-column label="隐患进度" width="150" prop="hiddenProgress" align="center"
              key="hiddenProgress"></el-table-column>
          </template>

          <template #actionButton="{ row }">
            <!-- <template
              v-if="
                row.hiddenState != 1 &&
                row.hiddenState != 2 &&
                row.hiddenState != 3
              "
            >
              <el-button type="text" @click="openApprovalDialog(1, row)"
                >通过</el-button
              >
              <el-button type="text" @click="openApprovalDialog(2, row)"
                >驳回</el-button
              >
            </template> -->
            <el-button type="text" icon="Edit" @click="handleEdit(row)" :disabled="row.hiddenProgress != '待审核' &&
              row.hiddenProgress != '待修改' &&
              row.hiddenProgress != '已驳回'
              " v-hasPermi="['preventionHiddenRegister:update']">修改</el-button>
            <el-button type="text" icon="Delete" style="color: red" @click="handleDel(row)"
              v-hasPermi="['preventionHiddenRegister:delete']">删除</el-button>
          </template>
        </Table>

        <DialogVform :formJson="formJson" ref="dialogVform" :slots="[
          'deptSlot',
          'typeSlot',
          'sonTypeSlot',
          'rectificationUserId',
          'reviewUserId',
          'fileSlot',
          'deviceId',
        ]" @onSubmit="onSubmit" title="隐患登记">
          <template #deviceId>
            <el-form-item label="装置" label-position="right">
              <el-select style="width: 100%" v-model="form.deviceId">
                <el-option v-for="it in zzData" :value="it.id" :label="it.deviceName"></el-option>
              </el-select>
            </el-form-item>
          </template>
          <template #deptSlot>
            <el-form-item label="所属部门" prop="deptId" label-position="right">
              <TreeSelect v-model="form.deptId" :options="deptTree" @change="changeDept" style="width: 100%">
              </TreeSelect>
            </el-form-item>
          </template>
          <template #fileSlot>
            <el-form-item label="文件上传" prop="fileId">
              <FileUpload :limit="5" :fileSize="30" :fileType="['png', 'jpeg', 'jpg']" v-model="files"></FileUpload>
            </el-form-item>
          </template>
          <template #typeSlot>
            <el-form-item label="隐患分类" label-position="right">
              <el-select @change="changeHiddenType" style="width: 100%" v-model="form.hiddenType">
                <el-option value="安全"></el-option>
                <el-option value="设备"></el-option>
                <el-option value="工艺"></el-option>
                <el-option value="操作"></el-option>
                <el-option value="电气"></el-option>
                <el-option value="仪表"></el-option>
                <el-option value="消防"></el-option>
                <el-option value="总图"></el-option>
                <el-option value="其他"></el-option>
              </el-select>
            </el-form-item>
          </template>

          <template #rectificationUserId>
            <el-form-item label="整改责任人" prop="rectificationUserId" label-position="right">
              <el-input v-model="form.rectificationUserName" readonly @click="onInnerOpen('rectificationUser')">
              </el-input>
            </el-form-item>
          </template>
          <template #reviewUserId>
            <el-form-item label="复核人" prop="reviewUserId" label-position="right">
              <el-input v-model="form.reviewUserName" readonly @click="onInnerOpen('reviewUser')"></el-input>
            </el-form-item>
          </template>

          <TableSelect ref="userTableSelect" :queryApi="listUser" :options="[]" :rowKey="'userId'" rowLabel="nickName"
            @onConfirm="onUserConfirm" rowLabelText="用户昵称" :maxNum="1">
            <template #formSlot="{ handleQuery, filterForm }">
              <el-col :span="8">
                <el-form-item label="部门名称">
                  <el-input size="small" @change="handleQuery" v-model="filterForm.deptName" clearable style="width: 100%"
                    @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="用户名称">
                  <el-input size="small" @change="handleQuery" v-model="filterForm.userName" clearable style="width: 100%"
                    @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
            </template>
            <template #tableSlot>
              <el-table-column label="部门" align="center" key="deptName" prop="dept.deptName" />
              <el-table-column label="用户名称" align="center" key="userName" prop="userName" />
              <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName" />
            </template>
          </TableSelect>
        </DialogVform>
      </el-col>
    </el-row>
    <el-dialog v-model="dialogFormVisible" title="审核意见">
      <el-input placeholder="请输入" v-model="approvalForm.hiddenStateInfo" type="textarea">
      </el-input>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="close">取 消</el-button>
          <el-button type="primary" @click="submitApp"> 确 认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import Table from "@/components/Table/index.vue";
import SearchForm from "@/components/searchForm/index";
import DialogVform from "@/components/dialogVform/index";
import formJson from "./components/options.json";
import { apis as APIS } from "@/api/yhpc/yhdj.js";
import { parseTime } from "@/utils/ruoyi.js";
import { useAsyncData, useFormJson } from "@/views/hooks/useAsyncData.js";
import { deptTreeSelect, listUser } from "@/api/system/user";
import FileUpload from "@/components/FileUpload";
import { selectOptions } from "./components/consts";
import TableSelect from "@/components/tableSelect/index";
import { pushInvestigation } from "@/api/yhpc/push";
const { proxy } = getCurrentInstance();
const ops = useFormJson(formJson, {
  sort: [],
  sortable: [],
});

const options = reactive({
  table: ops,
  formOps: ops.filter((i) =>
    ["hiddenSource", "hiddenType", "hiddenLevel", "hiddenCheckType"].includes(
      i.prop
    )
  ),
});
const files = ref([]);
const showSearch = ref(true);
const dialogVform = ref();
const deptTree = ref([]);
const table = ref();
const editRow = ref({});
const sonTypes = ref([]);
const userType = ref("");
const userTableSelect = ref();
const zzData = ref([]);
// 下拉框联动
const changeHiddenType = (val) => {
  sonTypes.value = selectOptions[val] || [];
};

const changeDept = (val, label) => {
  form.value.deptName = label;
  form.value.deptId = val;
};
// 审批
const dialogFormVisible = ref(false);
const approvalForm = ref({});
const openApprovalDialog = (type, row) => {
  dialogFormVisible.value = true;
  approvalForm.value.hiddenState = type;
  approvalForm.value.id = row.id;
};
const close = () => {
  dialogFormVisible.value = false;
  approvalForm.value.hiddenState = "";
  approvalForm.value.id = "";
  approvalForm.value.hiddenStateInfo = "";
};
const submitApp = () => {
  if (approvalForm.value.hiddenStateInfo) {
    APIS.updateHiddenState(approvalForm.value).then(() => {
      close();
      getList();
    });
  }
};

// 补充修改.新增事件
const plugEdit = (row) => {
  form.value.id = row.hiddenId;
  form.value.hiddenFrom = row.hiddenFrom;
  form.value.hiddenInventoryId = row.hiddenId;
  form.value.hiddenImageFileName = row.hiddenImageFileName;
  form.value.hiddenImageFileId = row.hiddenImageFileId;
  form.value.hiddenImageFileUrl = row.hiddenImageFileUrl;
  form.value.hiddenType = row.hiddenType;
  form.value.hiddenBelongType = row.hiddenBelongType;
  form.value.deptName = row.deptName;
  form.value.deptId = row.deptId;
  form.value.rectificationUserId = row.rectificationUserId;
  form.value.rectificationUserName = row.rectificationUserName;
  form.value.reviewUserId = row.reviewUserId;
  form.value.reviewUserName = row.reviewUserName;
  form.value.deviceId = row.deviceId;
  editRow.value = { ...row };
  if (row.fileManageList.length) {
    files.value = row.fileManageList;
  } else if (row.hiddenImageFileId) {
    files.value = [
      {
        name: row.hiddenImageFileName,
        id: row.hiddenImageFileId,
        url: row.hiddenImageFileUrl,
      },
    ];
  }
};

const plugAdd = () => {
  files.value = [];
  return {
    hiddenCheckUser: JSON.parse(localStorage.getItem("USER_INFO")).nickName,
    hiddenCheckTime: parseTime(new Date()),
  };
};
const getZzSelect = () => {
  APIS.zz().then((res) => {
    zzData.value = res.rows;
  });
};
const columnZz = (id) => {
  return zzData.value.find((item) => item.id == id)?.deviceName;
};
const onInnerOpen = (type) => {
  userType.value = type;
  const {
    rectificationUserId,
    rectificationUserName,
    reviewUserId,
    reviewUserName,
  } = form.value;
  let values = (rectificationUserId && rectificationUserId.split(",")) || [];
  let names = (rectificationUserName && rectificationUserName.split(",")) || [];
  if (type == "reviewUser") {
    values = (reviewUserId && reviewUserId.split(",")) || [];
    names = (reviewUserName && reviewUserName.split(",")) || [];
  }
  userTableSelect.value.open(
    values.map((item, index) => ({
      value: values[index],
      label: names[index],
    }))
  );
};
const onUserConfirm = (data) => {
  const values = data.map((item) => item.value);
  const names = data.map((item) => item.label);
  if (userType.value == "reviewUser") {
    form.value.reviewUserId = values.join(",");
    form.value.reviewUserName = names.join(",");
  } else {
    form.value.rectificationUserId = values.join(",");
    form.value.rectificationUserName = names.join(",");
  }
};
const {
  onSubmit,
  fetchData,
  dialogType,
  handleAdd,
  handleEdit,
  getList,
  handleDel,
  queryParams,
  form,
} = useAsyncData({
  APIS: {
    ...APIS,
    // query: APIS.querydj,
  },
  formJson,
  dialogVform,
  table,
  proxy,
  plugEdit,
  plugAdd,
});

watch(
  () => files,
  (newData) => {
    if (newData.value.length === 0) {
      form.value.hiddenFileId = "";
    } else {
      form.value.hiddenFileId = newData.value
        .map((item) => (item ? item.id : ""))
        .join(",");
      // form.value.hiddenImageFileName = newData.value[0].name;
      // form.value.hiddenImageFileId = newData.value[0].id;
      // form.value.hiddenImageFileUrl = newData.value[0].url;
    }
  },
  {
    deep: true,
  }
);
onMounted(() => {
  getZzSelect();
  deptTreeSelect().then((response) => {
    deptTree.value = response.data;
  });
});

const selectList = ref([]);
const selectionChange = (rows) => {
  selectList.value = rows;
};

const handlePush = () => {
  if (selectList.value.length == 0) {
    proxy.$modal.msgError("未选择数据");
    return;
  }
  pushInvestigation({
    ids: selectList.value.map((item) => item.id).join(","),
  }).then((res) => {
    if (res.msg.includes("成功")) {
      proxy.$modal.msgSuccess(res.msg);
    } else {
      proxy.$modal.msgError(res.msg);
    }
  });
};
</script>

<style lang="scss" scoped>
::v-deep.el-form-item__label {
  text-align: right !important;
}
</style>
